//
//  UITextArrachment+Extension.swift
//  表情键盘
//
//  Created by liyonggui on 16/5/25.
//  Copyright © 2016年 liyonggui. All rights reserved.
//

import UIKit

extension UITextView {
    
    /// 获取textView的带表情名称内容
    func emoticonNameText() -> String {
        var resultString = ""
        self.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: self.attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (info, range, _) -> Void in
            // 判断是否是附件
            if let attachment = info["NSAttachment"] as? YGTextAttachment {
                resultString += attachment.chs!
            } else {
                // 文字，emoji
                let text = (self.attributedText.string as NSString).substringWithRange(range)
                resultString += text
            }
        }
        return resultString
    }
    
    ///  将模型对应的内容添加到textView
    ///
    ///  - parameter emoticonModel: 模型
    func insertEmoticon(emoticonModel: YGEmoticonModel) {
        
        // 添加emoji表情
        if let emoji = emoticonModel.emoji {
            self.insertText(emoji)
        } else {
            // 图片
            // 附件
            let attachment = YGTextAttachment()
            // 设置图片
            attachment.image = UIImage(named: emoticonModel.imagePath!)
            // 设置附件大小
            let wh = self.font!.lineHeight * 0.85
            attachment.bounds = CGRect(x: 0, y: -3, width: wh, height: wh)
            // 设置附件的名称
            attachment.chs = emoticonModel.chs
            
            // 将附件转成属性文本
            let imageAttr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            // 附件缺少文本属性，后面的附件会变小
            imageAttr.addAttribute(NSFontAttributeName, value: self.font!, range: NSRange(location: 0, length: 1))
            
            // 获取之前的内容
            let beforeAttr = NSMutableAttributedString(attributedString: self.attributedText)
            // 获取textView选中的范围
            let textSelectedRange = self.selectedRange
            // 将带附件的属性文本替换到之前的内容里面
            beforeAttr.replaceCharactersInRange(textSelectedRange, withAttributedString: imageAttr)
            
            // 将设置后的属性文本赋值回来
            self.attributedText = beforeAttr
            
            // 设置关标位置
            self.selectedRange = NSRange(location: textSelectedRange.location + 1, length: 0)
        }
    }
    
}







































